﻿
namespace ZquenceStudio3Host.DspPlugins.Synthesizers.Nodesizer.Engine.Modules.Converters
{
    [ModuleDisplay("Midi Spread")]
    public class PitchSpreadModule : BaseModule
    {
        private double mSpread;

        private ModuleInput In;
        private ModuleOutput Out1;
        private ModuleOutput Out2;
        private ModuleOutput Out3;
        private ModuleOutput Out4;

        public PitchSpreadModule(ModuleManager manager)
            : base(manager)
        {
            AddInput(In = new ModuleInput("In", IOType.Midi, this));
            AddOutput(Out1 = new ModuleOutput("1.0", IOType.Midi, this));
            AddOutput(Out2 = new ModuleOutput("0.5", IOType.Midi, this));
            AddOutput(Out3 = new ModuleOutput("-0.5", IOType.Midi, this));
            AddOutput(Out4 = new ModuleOutput("-1.0", IOType.Midi, this));

            InputModuleParameter spread = new InputModuleParameter(this, "Spd", 1, IOType.Audio);
            spread.Display = "Spead";
            spread.MinValue = -1;
            spread.MaxValue = 1;
            spread.DirectGet += delegate { return mSpread; };
            spread.DirectSet += delegate (double value) { mSpread = value; };
            AddParameter(spread);
        }

        public override void Process()
        {
            if (In.IsConnected)
            {
                double spread = mSpread;
                int length = In.FromOutput.MidiBuffer.Count;
                for (int i = 0; i < length; i++)
                {
                    var midi = In.FromOutput.MidiBuffer[i];

                    var m1 = midi;
                    var m2 = midi;
                    var m3 = midi;
                    var m4 = midi;

                    if (midi.MidiData.Status == SoundEngine3.MIDI.Meta.MidiStatus.NOTE_ON)
                    {
                        m1.DetuneFloat += 1 * spread;
                        m2.DetuneFloat += 0.5 * spread;
                        m3.DetuneFloat += -0.5 * spread;
                        m4.DetuneFloat += -1.0 * spread;
                    }

                    Out1.AddMidiMessage(m1);
                    Out2.AddMidiMessage(m2);
                    Out3.AddMidiMessage(m3);
                    Out4.AddMidiMessage(m4);
                }
            }
        }
    }
}
